package com.fz.us.oa.web.controller.com;

import com.fz.us.admin.base.bean.BaseEnumManager;
import com.fz.us.admin.base.bean.jqgrid.JqGridFilter;
import com.fz.us.admin.base.bean.jqgrid.JqGridPager;
import com.fz.us.admin.base.bean.search.order.Order;
import com.fz.us.admin.base.bean.search.result.SearchResultPaging;
import com.fz.us.admin.base.utils.DataUtil;
import com.fz.us.admin.company.bean.FlowEnum;
import com.fz.us.admin.company.entity.Company;
import com.fz.us.admin.company.entity.TaskEntity;
import com.fz.us.admin.company.entity.User;
import com.fz.us.admin.company.service.DutyService;
import com.fz.us.admin.company.service.TaskEntityService;
import com.fz.us.oa.core.entity.com.PersonnelInfo;
import com.fz.us.oa.core.entity.com.PersonnelReward;
import com.fz.us.oa.core.entity.common.FileManage;
import com.fz.us.oa.core.service.com.PersonnelInfoService;
import com.fz.us.oa.core.service.com.PersonnelRewardService;
import com.fz.us.oa.core.service.common.FileManagerService;
import com.fz.us.oa.web.controller.BaseController;
import com.fz.us.oa.web.shiro.bind.annotation.CurrentUser;
import com.fz.us.oa.web.spring.bind.annotation.RequestJsonParam;
import com.google.common.collect.Lists;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by ZhuChunXiao on 2017/7/19.
 */
@Controller
@RequestMapping(value = "/com/personnelReward")
public class PersonnelRewardController extends BaseController {
    private static final long serialVersionUID = 6021032300428074215L;

    @Autowired
    private PersonnelRewardService personnelRewardService;
    @Autowired
    private PersonnelInfoService personnelInfoService;
    @Autowired
    private DutyService dutyService;
    @Autowired
    private TaskEntityService taskEntityService;
    @Autowired
    private FileManagerService fileManagerService;

    /**
     * 新建，编辑页面
     */
    @RequestMapping(value = "input", method = RequestMethod.GET, produces = MediaType.TEXT_HTML_VALUE)
    public String input(@CurrentUser User user, Model model,String keyId,String parentId,String draft,String index,String todo,String remind,String record) {
        if (StringUtils.isNotEmpty(keyId)){
            String fileId ="";
            PersonnelReward personnelReward=personnelRewardService.get(keyId);
            if(personnelReward.getFile() != null && personnelReward.getFile().size()>0){
                for(FileManage f:personnelReward.getFile()){
                    fileId+=f.getId()+",";
                }
            }
            model.addAttribute("personnelReward", personnelReward);
            model.addAttribute("fileId", fileId);
        }
        PersonnelInfo personnelInfo=personnelInfoService.get(parentId);
        model.addAttribute("personnelInfo", personnelInfo);
        model.addAttribute("draft", draft);
        model.addAttribute("index", index);
        model.addAttribute("todo", todo);
        model.addAttribute("remind", remind);
        model.addAttribute("record", record);
        return "/com/personnelReward_input";
    }

    /**
     * 只读页面
     */
    @RequestMapping(value = "read", method = RequestMethod.GET, produces = MediaType.TEXT_HTML_VALUE)
    public String read(@CurrentUser User user, Model model,String keyId,String draft,String index,String todo,String remind,String record) {
        if(StringUtils.isNotEmpty(keyId)) {
            String fileId ="";
            PersonnelReward personnelReward=personnelRewardService.get(keyId);
            if(personnelReward.getFile() != null && personnelReward.getFile().size()>0){
                for(FileManage f:personnelReward.getFile()){
                    fileId+=f.getId()+",";
                }
            }
            TaskEntity taskEntity = taskEntityService.getInfoByKeyId(keyId);
            int stepNo = taskEntity.getStepNo();
            String isEdit =  isEdit(keyId);
            model.addAttribute("fileId", fileId);
            model.addAttribute("isEdit", isEdit);
            model.addAttribute("personnelReward", personnelReward);
            model.addAttribute("stepNo", stepNo);
        }
        model.addAttribute("keyId", keyId);
        model.addAttribute("draft", draft);
        model.addAttribute("index", index);
        model.addAttribute("todo", todo);
        model.addAttribute("remind", remind);
        model.addAttribute("record", record);
        return "/com/personnelReward_read";
    }

    /**
     * 保存Model数据
     */
    private PersonnelReward saveModel(User user, String keyId, String type, String name, String date,
                                      String fileIds, String parentId) throws ParseException {

        PersonnelReward personnelReward=null;
        if(StringUtils.isBlank(keyId)){
            personnelReward = new PersonnelReward();
            personnelReward.setCreater(user);
            personnelReward.setCompany(user.getCompany());
        }else{
            personnelReward = personnelRewardService.get(keyId);
        }
        if(StringUtils.isNotEmpty(type)){
            personnelReward.setType(Integer.parseInt(type));
        }
        if(StringUtils.isNotEmpty(name)){
            personnelReward.setName(name);
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        if(StringUtils.isNotEmpty(date)){
            personnelReward.setDate(sdf.parse(date));
        }
        if(StringUtils.isNotEmpty(parentId)){
            personnelReward.setPersonnelInfo(personnelInfoService.get(parentId));
        }
        List<FileManage> fileManageList = Lists.newArrayList();
        if(StringUtils.isNotEmpty(fileIds)){
            for(String f:fileIds.split(",")){
                fileManageList.add(fileManagerService.get(f.trim()));
            }
        }
        personnelReward.setFile(fileManageList);

        return personnelReward;
    }

    /**
     * 保存操作
     */
    @RequestMapping(value = "save", method = RequestMethod.POST)
    public Object save(@CurrentUser User user,
                       @RequestParam(required = false) String keyId,
                       String type,
                       String name,
                       String date,
                       String fileIds,
                       String parentId) throws ParseException {

        Map<String,Object> rMap=new HashMap<String,Object>();
        PersonnelReward personnelReward=saveModel(user, keyId, type, name, date, fileIds, parentId);

        if(StringUtils.isNotEmpty(keyId)){
            personnelRewardService.update(personnelReward);
            rMap.put("message", "更新成功");
        } else {
            personnelRewardService.save(personnelReward, "com.fz.us.oa.core.entity.com.PersonnelReward");
            rMap.put("message", "保存成功");
        }
        rMap.put("state", "1");
        rMap.put("keyId", keyId);
        return ajaxJson(rMap);
    }

    /**
     * 提交操作
     */
    @RequestMapping(value = "submit", method = RequestMethod.POST)
    public Object submit(@CurrentUser User user,
                         @RequestParam(required = false) String keyId,
                         String type,
                         String name,
                         String date,
                         String fileIds,
                         String parentId,
                         String curDutyId,
                         String comment) throws ParseException {

        Map<String, Object> rMap = new HashMap<String, Object>();
        PersonnelReward personnelReward=saveModel(user,keyId,type,name,date,fileIds,parentId);

        if (StringUtils.isNotEmpty(keyId)) {
            personnelRewardService.approve(personnelReward, dutyService.get(curDutyId), comment);
        } else {
            personnelRewardService.commit(personnelReward, "com.fz.us.oa.core.entity.com.PersonnelReward", dutyService.get(curDutyId));
        }

        rMap.put("message", "提交成功");
        rMap.put("state", "1");
        rMap.put("keyId", keyId);
        return ajaxJson(rMap);
    }

    //审批
    @RequestMapping(value = "approve", method = RequestMethod.POST)
    public Object approve(@CurrentUser User user, String keyId,  String curDutyId, String comment){
        Map<String,Object> rMap=new HashMap<String,Object>();
        PersonnelReward personnelReward = personnelRewardService.get(keyId);
        personnelRewardService.approve(personnelReward, dutyService.get(curDutyId), comment);

        rMap.put("message","提交成功");
        rMap.put("state","1");
        rMap.put("keyId", keyId);
        return ajaxJson(rMap);
    }

    /**
     * 退回
     * @return
     */
    @RequestMapping(value = "back", method = RequestMethod.POST)
    public Object back(@CurrentUser User user, String keyId,String curDutyId, String comment) {
        if (StringUtils.isNotEmpty(keyId)) {
            PersonnelReward personnelReward = personnelRewardService.get(keyId);
            personnelRewardService.back(personnelReward, dutyService.get(curDutyId), comment);
        }
        Map<String,Object> rMap=new HashMap<String,Object>();
        rMap.put("message","退回成功");
        rMap.put("state","1");
        rMap.put("keyId", keyId);
        return ajaxJson(rMap);
    }
    /**
     * 否决
     * @return
     */
    @RequestMapping(value = "deny", method = RequestMethod.POST)
    public Object deny(@CurrentUser User user, String keyId,String curDutyId, String comment) {
        if (StringUtils.isNotEmpty(keyId)) {
            PersonnelReward personnelReward = personnelRewardService.get(keyId);
            personnelRewardService.deny(personnelReward, dutyService.get(curDutyId), comment);
        }
        Map<String,Object> rMap=new HashMap<String,Object>();
        rMap.put("message","否决成功");
        rMap.put("state","1");
        rMap.put("keyId", keyId);
        return ajaxJson(rMap);
    }

    /**
     * 进入list页面
     */
    @RequestMapping(value = "toList", method = RequestMethod.GET, produces = MediaType.TEXT_HTML_VALUE)
    public String toList(Model model,String parentId) {

        model.addAttribute("parentId", parentId);

        return "/main/menu/com/personnelReward_in";
    }

    /**
     * 列表
     */
    @RequestMapping(value = "list", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public Map<String, Object> list(@CurrentUser User user,Model model,
                                    String viewtype,
                                    JqGridPager pager,
                                    String parentId,
                                    @RequestJsonParam(value = "filters", required = false) JqGridFilter filters) {
        Company company = user.getCompany();
        // 排序
        Order order = null;

        SearchResultPaging searchResult = null;
        Map<String,Object> params = new HashMap<String,Object>();
        PersonnelInfo personnelInfo=personnelInfoService.get(parentId);
        params.put("company", company);
        params.put("state", BaseEnumManager.StateEnum.Enable);
        //当前用户的单子
        params.put("personnelInfo", personnelInfo);
        searchResult = personnelRewardService.paging(null,null,order,
                "com.fz.us.oa.core.entity.com.PersonnelReward",
                new FlowEnum.ProcessState []{FlowEnum.ProcessState.Finished, FlowEnum.ProcessState.Running}, params);


        List<PersonnelReward> personnelRewardList = searchResult.getList();
        ArrayList<Map<String, Object>> dataRows = new ArrayList<Map<String, Object>>();
        Map<String, Object> data = new HashMap<String, Object>();
        Map<String,Object> rMap;
        for(PersonnelReward personnelReward: personnelRewardList){
            rMap = new HashMap<String, Object>();
            rMap.put("id", StringUtils.isEmpty(personnelReward.getId())?"":personnelReward.getId());
            rMap.put("name", StringUtils.isEmpty(personnelReward.getName())?"":personnelReward.getName());
            rMap.put("date", personnelReward.getDate()==null?"":DataUtil.DateToString(personnelReward.getDate()));
            if(personnelReward.getType()==1){
                rMap.put("type", "奖励");
            }else if(personnelReward.getType()==2){
                rMap.put("type", "惩罚");
            }else{
                rMap.put("type", "未知");
            }
            dataRows.add(rMap);
        }
        data.put("dataRows", dataRows);
        data.put("page", searchResult.getPageNumber());
        data.put("rows", searchResult.getPageSize());
        data.put("records", searchResult.getTotalCount());
        data.put("total", searchResult.getPageCount());
        return data;
    }
}
